﻿using System.Linq;
using Daemon.Common;
using Daemon.Common.Helpers;
using Daemon.Infrustructure.EF;
using Daemon.Repository.EF.Enums;
using Daemon.Repository.Contract;
using Daemon.Model;
using System;
using System.Linq.Expressions;
using System.Collections.Generic;

namespace Daemon.Repository.EF
{
    public class DeptRepository : Repository<Department>, IDeptRepository
    {
        protected override Expression<Func<Department, int>> PrimaryKeyExpression => r => r.Id;

        public DeptRepository(ApiDBContent context) : base(context)
        {
        }

        protected override void UpdateEntitiesAfterDelete(IEnumerable<Department> entities, ApiDBContent context)
        {
            var deptIds = entities.Select(r => r.Id).ToList();
            var childDepartments = context.Departments.Where(r => deptIds.Contains(r.FatherId));
            if (childDepartments.Any())
            {
                DeleteRangeByDBContext(childDepartments, context);
            }
        }

        private List<Department> GetChildren(List<Department> departments, int parentId, List<Department> result = null)
        {
            if (result == null)
            {
                result = new List<Department>();
            }

            var children = departments.Where(r => r.FatherId == parentId).ToList();
            if (children.Any())
            {
                result.AddRange(children);
                children.ForEach(child =>
                {
                    GetChildren(departments, child.Id, result);
                });
            }

            return result;
        }
    }
}
